import './../public-path.js'
import Vue from 'vue'
import App from './main.vue'
import VueRouter from 'vue-router'
import store from '../../store'
import ElementUI from 'element-ui'
// import 'default-passive-events'
import '../../../theme/index.css'
import '../../assets/iconfont/iconfont.css'
import '../../assets/iconfont/iconfont.js' // 多色图标
import '../../common/style/base.styl'
import { Component } from 'vue-property-decorator'
// import VueI18n from 'vue-i18n'
import { CommonModule } from '@/store/modules/common'
import { LoginModule } from '@/store/modules/login'
import { commonAction } from '@/utils/common'
import { WebchatModule } from '@/store/modules/webchat'
import { SocketModule } from '@/store/modules/socket'
import EventBus from 'vue-bus-ts'
import m7getCache from '@/utils/m7getCache'
import '@components/IconSvg' // 全局icon 多色图标组件
import '@/components/select' // 全局的m7select组件
import router from '@/router/handleRoute.js'
Vue.config.productionTip = false
Vue.use(VueRouter)
Vue.use(ElementUI, {
  zIndex: 1800
})
// Vue.use(VueI18n)
Vue.use(EventBus)
Vue.use(m7getCache)

const bus = new EventBus.Bus()
export let instance: any = null
export let microRouter: any = null

function render (props) {
  const { // qiankun环境，需要什么参数先定义
    store: microStore,
    container
  } = props
  const baseUrl = props.store ? props.store.baseRoute : ''
  microRouter = new VueRouter({
    // @ts-ignore
    base: baseUrl,
    mode: 'history',
    routes: [
      {
        meta: { hidden: false },
        name: 'webchatCard',
        path: '/im_workBench/index/:activeName/:id',
        component: () => import(/* webpackChunkName: "webchatCard" */ '@views/webchat/webchatSummary.vue')
      }
    ]
  })
  instance = new Vue({
    store,
    router: microRouter,
    bus,
    render: h => h(App),
    data () {
      return {
        microStore,
        loginInfo: {}
      }
    }
  }).$mount(container ? container.querySelector('#microWebchat') : '#microWebchat')
}
async function loginByToken (tokenStr: string) { // token登录
  const tokenResp = await commonAction({ url: '/auth/login/token', method: 'POST', data: { ssoToken: tokenStr } })
  if (tokenResp && tokenResp.success && tokenResp.data) {
    const respData = {
      info: {
        loginName: tokenResp.data.loginName,
        password: tokenResp.data.password,
        loginType: tokenResp.data.loginType,
        isComplexPass: true
      }
    }
    login(respData, () => {
      render({})
    })
  } else {
    return tokenResp
  }
}
const token = getQueryString('token')
if (token && token.toString().length > 1) {
  loginByToken(token)
}
// if (!window.__POWERED_BY_QIANKUN__) {
//   const loginObj = { info: { loginName: '8888@7mqd3', password: 'MTIzNDU2QWE=' } }
//   login(loginObj, () => {
//     render({})
//   })
// }
function getQueryString (name: string) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

function login (loginObj: any, callBack?: any) {
  const { loginName, password, isComplexPass } = loginObj.info
  const actionData = { url: '/base/public/platform-info', method: 'GET', data: { domain: window.location.href.split('/')[2] } }
  LoginModule.LoginCommonAction(actionData).then((res: any) => {
    if (res && res.success) {
      CommonModule.setInitConfig(res.data || {})
      const longinData = {
        url: '/sdkapis/auth/action/sdk/login',
        method: 'POST',
        data: { loginName, password, loginChannel: 'imSdk', isComplexPass: isComplexPass || false }
      }
      CommonModule.SET_CURRENT_ENV()
      if (loginObj.loginInfo && Object.keys(loginObj.loginInfo).length > 0) {
        loginSuccessCallback(loginObj.loginInfo, 'logined', () => {
          callBack()
        })
      } else {
        LoginModule.LoginCommonAction(longinData).then((loginRes: any) => {
          if (loginRes && loginRes.success) {
            if (loginObj.store) {
              loginObj.store.getLoginInfo(loginRes) // 把登录信息给主应用
            }
            loginSuccessCallback(loginRes, 'init', () => {
              callBack()
            })
          } else {
            if (loginObj.store) {
              loginObj.store.loginError(loginRes)
            }
          }
        }).catch(error => {
          if (loginObj.store) {
            loginObj.store.loginError(error)
          }
        })
      }
    }
  })
}

function loginSuccessCallback (loginRes: any, type: string, callBack?: any) {
  const resData = loginRes.data || {}
  CommonModule.setSession(resData) // 设置session信息
  const webchatStatus = { status: 'open', _id: '' }
  if (type === 'init') {
    SocketModule.initSocket({ data: loginRes.data, isLogin: true, webchatStatus }) // 注册socket
  }
  // 获取在线emoji配置
  CommonModule.publicAction({ url: '/im-center/action/webchat/getEmojiConfig', method: 'POST' }).then(emoji => {
    if (emoji && emoji.success && emoji.data) {
      WebchatModule.SET_EMOJICONFIG(emoji.data)
    }
  })
  const commonTypes = ['userList', 'queueList', 'commonAppIdList'] // 座席，技能组列表，一级菜单列表, 常用应用列表
  const p1 = commonAction({ url: '/base/action/general/cache/query', method: 'POST', data: { types: commonTypes } }) // 通用的基础缓存
  return Promise.all([p1]).then(([commonRes]) => {
    commonTypes.forEach((item: string) => {
      CommonModule.setPublicCache({ data: commonRes[item] ? commonRes[item] : [], type: item, hasObj: true })
    })
    callBack()
  })
}

export async function bootstrap () {
  console.log('vue app bootstraped')
}

export async function mount (props: any) {
  console.log('props from main app', props)
  login(props, () => {
    render(props)
  })
}
export async function update (props: any) {
  if (props.sendInfo) { // 发送在线消息
    instance.$bus.$emit('sendInfo', props.sendInfo)
  }
  if (props.status) { // 更改在线状态
    const actionData = { url: '/im-center/action/user/status/update', method: 'POST', data: { _id: props.status } }
    WebchatModule.webchatCommonAction(actionData).then(res => {
      const isSuccess = !!(res && res.success)
      const microStore = instance.$root.microStore
      if (microStore && microStore.statuFun) {
        microStore.statuFun(() => {
          return isSuccess
        })
      }
    })
  }
  if (props.uploadInfo) { // （更新|| 新增） 客户
    const obj = {
      webchatDetails: {
        _id: props.uploadInfo.sessionId
      },
      custName: props.uploadInfo.customerName
    }
    WebchatModule.UPDATE_CUSTOMER_INFO(obj)
  }
}
export async function unmount () {
  instance.$destroy()
  instance.$el.innerHTML = '' // 防止内存泄漏，子项目销毁时清空dom
  instance = null
}

Component.registerHooks([
  'beforeRouteEnter', // 路由进入组件时，实例还没有创建，无法获取到this
  'beforeRouteLeave', // 导航离开组件的对应路由时调用,能获取到this
  'beforeRouteUpdate' // 路由修改，当前组件被复用时调用,能获取到this
])
